<template>
  <div>
    <div style="margin: -14px 0px 0px; padding: 2px 0px">
      <a-card :bordered="false">
        <a-form>
          <!-- <a-row :gutter="12">
            <a-col :span="6">
              <div style="display: flex; align-items: center">
                <span style="width: 100px">登记时间:</span>
                  <a-range-picker :allow-clear="true"  v-model="day" style="width: 100%">
                  <a-icon slot="suffixIcon" type="calendar" />
                </a-range-picker>
              </div>
            </a-col>
            <a-col :span="6">
              <span class="searchItem">
                <span>活动名称:</span
                ><a-input v-model.trim="searchDB.activityName" allow-clear style="width: 200px"></a-input>
              </span>
            </a-col>
            <a-col :span="4">
              <div>
                <a-button type="primary" style="margin: 0 10px" @click="search('search')">搜索</a-button>
                <a-button @click="reset">重置</a-button>
              </div>
            </a-col>
          </a-row> -->

          <a-row :gutter="12">
            <a-col :md="6">
              <div class="package-search-box">
                <span style="width: 100px">套餐名称：</span>
                <a-input v-model.trim="searchDB.activityName" allow-clear placeholder="请输入套餐名称" @keydown.enter="search"></a-input>
              </div>
            </a-col>
            <a-col :md="6">
              <div style="display: flex; align-items: center; padding-right: 10px">
                <span style="width: 100px">登记时间:</span>
                <a-range-picker :allowClear="true" v-model="day" style="width: 100%">
                  <a-icon slot="suffixIcon" type="calendar" />
                </a-range-picker>
              </div>
            </a-col>
            <a-col :md="5" :sm="24">
              <div class="package-search-box">
                <span style="width: 80px">启用状态：</span>
                <!-- <a-switch @change="isDisabledChange" />  -->
                <a-select
                  class="package-search-box-input"
                  placeholder="请选择"
                  allowClear
                  v-model.trim="searchDB.isDisabled"
                >
                  <a-select-option :value="undefined">
                    <div>请选择</div>
                  </a-select-option>
                  <a-select-option :value="0">
                    <div>已启用</div>
                  </a-select-option>
                  <a-select-option :value="1">
                    <div>未启用</div>
                  </a-select-option>
                </a-select>
              </div>
            </a-col>

            <a-col :md="7">
              <div>
                <a-button type="primary" style="margin: 0 10px" @click="search('search', 'one')">搜索</a-button>
                <a-button @click="reset">重置</a-button>
              </div>
            </a-col>
          </a-row>
          <a-row :gutter="12">
            <a-col :md="5" :sm="24">
              <div class="package-search-box" style="margin-bottom:0px;">
                <span style="width: 80px">过期状态：</span>
                <!-- <a-switch @change="isDisabledChange" />  -->
                <a-select
                  class="package-search-box-input"
                  placeholder="请选择"
                  allowClear
                  v-model.trim="searchDB.overdueDate"
                >
                  <a-select-option :value="undefined">
                    <div>请选择</div>
                  </a-select-option>
                  <a-select-option :value="2">
                    <div>已过期</div>
                  </a-select-option>
                  <a-select-option :value="1">
                    <div>未过期</div>
                  </a-select-option>
                </a-select>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </div>
    <div style="margin: 8px 0px; padding: 2px 0px">
      <a-card :bordered="false" style="display: flex; flex-direction: column">
        <a-button type="primary" style="border-radius: 50px; margin: 10px" @click="add('1')">新增活动</a-button>
        <a-table
          @expand="ca"
          @change="handleTableChange"
          :expanded-row-keys="ExpandedRowKeys"
          :columns="columns"
          :data-source="data"
          :loading="loading"
          :pagination="pagination"
          :rowKey="(record) => record.tbActivityId"
          class="components-table-demo-nested"
        >
          <a slot="operation" slot-scope="text, record">
            <span @click="add('2', record)">修改</span>
            <!-- <span style="margin: 0 10px">复制</span> -->
          </a>
          <span slot="tags" slot-scope="tags">
            <a-tag :color="tags === '已启用' ? '#39f' : '#d9d9d9'">
              {{ tags }}
            </a-tag>
          </span>
          <span slot="subTags" slot-scope="subTags">
            <a-tag :color="subTags === '已过期' ? '#d9d9d9' : 'green'">
              {{ subTags }}
            </a-tag>
          </span>
          <a-table
            :rowKey="
              (record, index) => {
                return record.itemId + index
              }
            "
            :loading="openLoading"
            slot="expandedRowRender"
            :pagination="false"
            :columns="innerColumns"
            :data-source="innerData"
            id="innerTable"
          >
            <span slot="abled" slot-scope="abled">
              <a-tag :color="abled === '已启用' ? '#39f' : '#d9d9d9'">
                {{ abled }}
              </a-tag>
            </span>
            <template slot="footer">
              <div v-if="loadMore" @click="loadMores">
                <a-button type="primary"  style="width: 300px; border: 1px solid #e1e2e3;margin: 0 auto;display: block;">加 载 更 多</a-button>
              </div>
            </template>
            <span slot="operation" class="table-operation">
              <a>删除</a>
            </span>
          </a-table>
        </a-table>
      </a-card>
    </div>

    <!--弹框-->
    <a-modal
      title="活动设置"
      width="500px;"
      
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :form="form">
        <a-form-item style="margin-bottom: 0px">
          <a-row :gutter="24">
            <a-col :md="8">
              <div class="searchItem">
                <a-form-item label="活动名称" class="formItem" style="margin-bottom: 10px">
                  <a-input
                    placeholder="请输入活动名称"
                    v-decorator="['activityName', { rules: [{ required: true, message: '请输入！' }] }]"
                    style="width: 180px"
                  ></a-input>
                </a-form-item></div
            ></a-col>
            <!-- <a-col :span="8">
              <div class="searchItem" style="margin: 0 2px">
                <a-form-item label="套餐类型" class="formItem">
                  <a-select
                    style="width: 225px"
                    @change="handleChange"
                    v-decorator="['ptype', { rules: [{ required: true, message: '请输入！' }] }]"
                  >
                    <a-select-option v-for="item in isType" :key="item.id" :isdisabled="item.label" :value="item.label">
                      <div>{{ item.value }}</div>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </div>
            </a-col> -->
            <a-col :md="12">
              <div style="display: flex">
                <a-form-item label="登记时间" class="formItem" style="margin-bottom: 10px">
                  <a-range-picker
                    allow-clear
                    v-decorator="['registDate', { rules: [{ required: true, message: '请输入！' }] }]"
                    style="width: 100%"
                  >
                    <a-icon slot="suffixIcon" type="calendar" />
                  </a-range-picker>
                </a-form-item>
              </div>
            </a-col>
            <a-col :md="4">
              <a-form-item label="启用状态" class="formItem" style="margin-bottom: 10px">
                <a-switch
                  v-decorator="[
                    'isDisabled',
                    { valuePropName: 'checked', rules: [{ required: false, message: '请输入！' }] },
                  ]"
                ></a-switch>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form-item>

        <a-form-item label="备注" style="margin-bottom: 10px">
          <a-row :gutter="48">
            <a-col :span="12">
              <a-textarea
                placeholder="请填写备注"
                v-decorator="['remark', { rules: [{ required: true, message: '请输入！' }] }]"
              />
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="选择明细">
          <a-popover placement="right" v-model="ShowPopover" trigger="click">
            <a slot="content" @click="hide" style="display: flex">
              <span style="margin-left: auto">×</span>
            </a>
            <template slot="content">
              <a-row :gutter="24">
                <!-- <a-col :span="8">
                  <div class="searchItem" style="margin: 10px 0">
                    <span>拼音码</span><a-input placeholder="请输入"></a-input>
                  </div>
                </a-col> -->
                <a-col :span="15">
                  <div class="searchItem" style="margin: 10px 0">
                    <span>名称</span
                    ><a-input
                      placeholder="请输入产品或项目名称"
                      v-model.trim="typeDB.name"
                      @keydown.enter.native="send(0)"
                    ></a-input>
                  </div>
                </a-col>
                <!-- <a-button @click="send">test</a-button> -->
                <a-col :span="9" style="line-height: 49px">
                  <div style="display: flex; align-items: center">
                    <span
                      >数据来源：
                      <a-switch
                        style="margin-left: 5px; margin-top: -6px"
                        checked-children="项目"
                        un-checked-children="产品"
                        v-model="typeState"
                        @change="getType"
                      ></a-switch
                    ></span>
                  </div>
                </a-col>
              </a-row>

              <a-table
                :rowKey="
                  (record, idx) => {
                    return record.id + idx
                  }
                "
                :columns="detaiColumns"
                :customRow="clicks"
                :data-source="detailed"
                :loading="detailLoading"
                :pagination="typepagination"
                @change="typeChange"
              >
                <a slot="name" slot-scope="text">{{ text }}</a>
              </a-table>
            </template>
            <a-button type="primary">新增</a-button>
          </a-popover>
        </a-form-item>
        <a-form-item>
          <a-table
            :columns="columnsSet"
            :data-source="packageDetail"
            :loading="loadingItem"
            :pagination="false"
            :rowKey="
              (record, idx) => {
                return idx
              }
            "
            class="add-table-style"
          >
            <template slot="originalPrice" slot-scope="text, record">
              {{text && (Number(text) / Number(record.times).toFixed('2'))}}
            </template>
            <template slot="useTimes" slot-scope="text, record, index">
              <a-input-number
                placeholder="请输入数量"
                :min="1"
                :value="text"
                @change="(value) => textChange2(value, record, index)"
              ></a-input-number>
            </template>
            <template slot="activityPrice" slot-scope="text, record, index">
              <a-input-number
                placeholder="请输入活动价"
                :min="0" 
                :value="text"
                @change="(value) => textChange(value, record, index)"
              ></a-input-number>
            </template>
            <span slot="operation" slot-scope="text, record, index" class="table-operation">
              <a-popconfirm title="删除该项数据?" @confirm="() => removeItem(record, index)">
                <a>删除</a>
                <!-- <a href="javascript:;">Delete</a> -->
              </a-popconfirm>
            </span>
            <template slot="footer">
              <span style="margin: 0 10px; font-size: 13px"
                >项目合计：<span style="color: #3399ff; font-size: 17px; font-weight: bold; margin: 0 5px">{{
                  TotalProject
                }}</span></span
              >
              <!-- <div style="display: inline-flex; align-items: center">
                <span style="margin: 0 10px; font-size: 13px">
                  套餐合计：<span style="color: red; font-size: 17px; font-weight: bold; margin: 0 5px"
                    ><i>¥</i> {{ TotalPrice }}</span
                  >
                </span>
              </div> -->
            </template>
          </a-table>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="less">
/**f0faff */
/deep/ .ant-modal {
  width: 1280px !important;
}
.formItem {
  display: inline-flex !important;
}
/deep/ .ant-modal {
  width: 999px;
}
/deep/ .ant-popover-inner-content {
  width: 500px !important;
}
.searchItem {
  display: flex;
  align-items: center;
}
.searchItem span {
  width: 100px;
}
/deep/ #innerTable .ant-table-thead {
  background-color: #f0faff !important;
}
/deep/ #innerTable .ant-table-thead > tr > th {
  background: none !important;
}
/deep/ .ant-table-expanded-row > td:first-child {
  display: none !important;
}
/deep/ .add-table-style .ant-table-footer {
  /* display:flex; */
  padding: 8px 16px;
  text-align: right;
  line-height: 29px;
}
/deep/ .add-table-style .ant-table-tbody > tr > td{
  padding: 10px 16px !important;
}
.package-search-box {
  display: flex;
  line-height: 30px;
  margin-bottom: 24px;
  padding-right: 10px;
}
.package-search-box .package-search-box-input {
  width: calc(100% - 90px);
}
</style>

<script>
const columns = [
  { title: '活动名称', align: 'center', width: 150, dataIndex: 'activityName', key: 'activityName', ellipsis: true },
  {
    title: '启用状态',
    align: 'center',
    // width:100,
    dataIndex: 'tags',
    key: 'tags',
    scopedSlots: {
      customRender: 'tags',
    },
  },
  {
    title: '过期状态',
    align: 'center',
    key: 'subTags',
    // width:100,
    dataIndex: 'subTags',
    scopedSlots: {
      customRender: 'subTags',
    },
  },
  {
    title: '开始时间',
    align: 'center',
    // width:120,
    dataIndex: 'beginDate',
    key: 'beginDate',
    customRender: (beginDate) => {
      return beginDate.length != '' ? beginDate : '-'
    },
  },
  {
    title: '结束时间',
    align: 'center',
    // width:120,
    dataIndex: 'endDate',
    key: 'endDate',
    customRender: (endDate) => {
      if (!endDate) {
        return '-'
      } else {
        return endDate
      }
    },
  },
  {
    title: '创建人',
    align: 'center',
    // width:120,
    dataIndex: 'recorder',
    key: 'recorder',
    customRender: (recorder) => {
      if (!recorder) {
        return '-'
      } else {
        return recorder
      }
    },
  },
  {
    title: '创建时间',
    align: 'center',
    // width:120,
    ellipsis: true,
    dataIndex: 'recordDate',
    key: 'recordDate',

    customRender: (recordDate) => {
      if (!recordDate) {
        return '-'
      } else {
        return recordDate
      }
    },
  },
  {
    title: '修改人',
    align: 'center',
    // width:120,
    dataIndex: 'modifier',
    key: 'modifier',
    customRender: (modifier) => {
      if (!modifier) {
        return '-'
      } else {
        return modifier
      }
    },
  },
  {
    title: '修改时间',
    align: 'center',
    // width:120,
    dataIndex: 'modifyDate',
    key: 'modifyDate',
    ellipsis: true,
    customRender: (modifyDate) => {
      if (modifyDate == '') {
        return '-'
      } else {
        return modifyDate
      }
    },
  },
  {
    title: '备注',
    align: 'center',
    // width:200,
    dataIndex: 'remark',
    key: 'remark',

    ellipsis: true,
    customRender: (remark) => {
      if (!remark) {
        return '-'
      } else {
        return remark
      }
    },
  },
  {
    title: '操作',
    key: 'operation',
    scopedSlots: { customRender: 'operation' },
    // width: 80,
    // fixed: 'right'
  },
]

const innerColumns = [
  {
    title: '名称',
    dataIndex: 'itemName',
    key: 'itemName',
    align: 'center',
    width: 300,
    ellipsis: true,
    customRender: (itemName) => {
      if (!itemName) {
        return '-'
      } else {
        return itemName
      }
    },
  },
  {
    title: '数量',
    align: 'center',
    dataIndex: 'useTimes',
    key: 'useTimes',
    customRender: (useTimes) => {
      if (!useTimes) {
        return '-'
      } else {
        return useTimes
      }
    },
  },
  {
    title: '单位',
    align: 'center',
    dataIndex: 'unit',
    key: 'unit',
    customRender: (unit) => {
      if (!unit) {
        return '-'
      } else {
        return unit
      }
    },
  },
  {
    title: '原单价',
    align: 'center',
    dataIndex: 'price',
    key: 'price',
    customRender: (price) => {
      if (price == undefined || price == null) {
        return '-'
      } else {
        return price.toFixed('2')
      }
    },
  },
  {
    title: '原总价',
    align: 'center',
    dataIndex: 'originalPrice',
    key: 'originalPrice',
    customRender: (originalPrice) => {
      if (originalPrice == undefined || originalPrice == null) {
        return '-'
      } else {
        return originalPrice.toFixed('2')
      }
    },
  },
  {
    title: '活动价',
    align: 'center',
    dataIndex: 'activityPrice',
    key: 'activityPrice',
    customRender: (activityPrice) => {
      if (activityPrice == undefined || activityPrice == null) {
        return '-'
      } else {
        return activityPrice.toFixed('2')
      }
    },
  },
  {
    title: '禁用',
    align: 'center',
    key: 'abled',
    dataIndex: 'abled',
    scopedSlots: {
      customRender: 'abled',
    },
  },
]
const innerData = []

import moment from 'moment'
import { axios } from '@/utils/request'
import { getItemDetailById } from '@/api/modular/main/customer/customerScene'
// import { SuperTable, XCard, XDown } from '@/components'
import {
  getActivity,
  getActivityDetail,
  addActivity,
  editActivity,
  removeItem,
  search,
  searchType,
  detail,
} from '@/api/bd/activity'
export default {
  watch: {
    packageDetail() { 
      if (this.packageDetail && this.packageDetail.length > 0) {
        this.TotalProject = this.packageDetail.length
        this.TotalPrice = this.packageDetail.map((item) => item.activityPrice).reduce((a, b) => a + b)
      } else {
        this.TotalProject = '0'
        this.TotalPrice = '0'
      }
    },
    ShowPopover() {
      if (this.ShowPopover) {
        this.typeState = false 
        this.typeDB.name = ''
        this.typeQueryParam.pageNum = 1
        this.typeQueryParam.pageSize = 10
        this.typepagination.current = 1
        this.typeDB = Object.assign({},this.typeDB)
        this.getType(false)
      }
    },

    type() { 
      this.typeQueryParam.pageNum = 1
      this.typeQueryParam.pageSize = 10
      this.typepagination.current = 1
      this.typeDB.pageNum = 1
      this.typeDB.pageSize = 10
      if (this.typeDB.name != '') {
        this.send(0)
      }
    },
    data(){
      this.$nextTick(() => {
        let target = document.getElementsByClassName('ant-table-expanded-row')
        for (var i = 0; i < target.length; i++) {
          target[i].childNodes[1].colSpan = 12 //这货根据数量来推格子的?
        }
      })
    },
    
  },
  data() {
    return {
      loadMore: false,
      loadingItem: false,
      type: '',
      name: '',
      typeDB: {
        pageNum: 1,
        pageSize: 10,
        name: '',
      },
      typepagination: {
        current: 1,
        total: 0,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'], //每页中显示的数据
      },
      innerPagination: {
        total: 0,
        pageSize: 20, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'], //每页中显示的数据
      },
      pagination: {
        current: 1,
        type: '',
        total: 0,
        pageSize: 20, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
      queryParams: {
        pageNum: 1,
        pageSize: 20,
      },

      Rrecord: {},
      typeState: false,
      detailLoading: false,
      day: [],
      searchDB: {
        pageSize: 20,
        pageNum: 1,
        code: undefined,
        activityName: undefined,
        beginDate: undefined,
        endDate: undefined,
        pycode: undefined,
        isDisabled: undefined,
        overdueDate: undefined,
      },
      TotalProject: '0',
      TotalPrice: '0',
      changeCloumns: [],
      changeDb: [],
      detaiColumns: [
        {
          title: '名称',
          dataIndex: 'itemName',
          key: 'name',
          customRender: (itemName) => {
            if (!itemName) {
              return '-'
            } else {
              return itemName
            }
          },
        },
        {
          title: '单位',
          dataIndex: 'packagePrice',
          key: 'packagePrice',
          customRender: (packagePrice) => {
            if (!packagePrice) {
              return '-'
            } else {
              return packagePrice
            }
          },
        },
        {
          title: '规格',
          dataIndex: 'itemUnit',
          key: 'itemUnit',
          customRender: (itemUnit) => {
            if (!itemUnit) {
              return '-'
            } else {
              return itemUnit
            }
          },
        },
        {
          title: '价格',
          dataIndex: 'price',
          key: 'price',
          customRender: (price) => {
            if (!price) {
              return '-'
            } else {
              return price.toFixed('2')
            }
          },
        },
        {
          title: '数量',
          dataIndex: 'useTimes',
          key: 'useTimes',
          customRender: (useTimes) => {
            if (!useTimes) {
              return '-'
            } else {
              return useTimes
            }
          },
        },
        {
          title: '执行科室',
          dataIndex: 'execDeptName',
          key: 'execDeptName',
          customRender: (execDeptName) => {
            if (!execDeptName) {
              return '-'
            } else {
              return execDeptName
            }
          },
        },
      ],
      columnsSet: [
        {
          title: '名称',
          align: 'center',
          dataIndex: 'itemName',
          key: 'itemName',
          customRender: (itemName) => {
            if (!itemName) {
              return '-'
            } else {
              return itemName
            }
          },
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit',
          key: 'unit',
          customRender: (unit) => {
            if (!unit) {
              return '-'
            } else {
              return unit
            }
          },
        },
        {
          title: '原价',
          align: 'center',
          dataIndex: 'originalPrice',
          key: 'originalPrice',
          scopedSlots: { customRender: 'originalPrice' },
          // customRender: (money) => {
          //   if (money == undefined || money == null) {
          //     return '-'
          //   } else {
          //     return money.toFixed('2')
          //   }
          // },
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'useTimes',
          key: 'useTimes',
          // customRender: (useTimes) => {
          //   if (!useTimes) {
          //     return '-'
          //   } else {
          //     return useTimes
          //   }
          // },
          scopedSlots: { customRender: 'useTimes' },
        },
        {
          title: '执行科室',
          align: 'center',
          dataIndex: 'execDeptName',
          key: 'execDeptName',
          customRender: (ex) => {
            if (!ex) {
              return '-'
            } else {
              return ex
            }
          },
        },
        {
          title: '活动价',
          align: 'center',
          dataIndex: 'activityPrice',
          key: 'activityPrice',
          // customRender: (activityPrice) => {
          //   if (!activityPrice) {
          //     return '-'
          //   } else {
          //     return activityPrice.toFixed('2')
          //   }
          // },
          scopedSlots: { customRender: 'activityPrice' },
        },
        { title: '操作', key: 'operation', scopedSlots: { customRender: 'operation' } },
      ],
      packageDetail: [],
      registDate: [],
      dateFormat: 'YYYY/MM/DD',
      detailed: [],
      tableType: [
        { id: 0, value: '产品', label: '1' },
        { id: 1, value: '项目', label: '2' },
      ],
      isType: [
        {
          id: 0,
          value: '当月套餐',
          label: '2',
        },
        {
          id: 1,
          value: '长期套餐',
          label: '1',
        },
      ],
      queryParam: {
        pageNum: 1,
        pageSize: 20,
        id: undefined,
      },
      typeQueryParam: {
        pageNum: 1,
        pageSize: 50,
      },
      isDisabled: 0,
      ShowPopover: false,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),

      visible: false,
      Title: '',
      data: [],
      columns,
      innerColumns,
      innerData,
      loading: false,
      ExpandedRowKeys: [],

      temporary: {
        isEx: false,
        record: {}
      },

      // 展开的loading
      openLoading: false
    }
  },
  // components: { SuperTable },
  mounted() {
    this.getList()
  },
  methods: {
    textChange(value, row, index) {
      this.packageDetail[index].activityPrice = value
      this.packageDetail = [...this.packageDetail]
    },
    textChange2(value, row, index) { 
      this.packageDetail[index].useTimes = value
      this.packageDetail[index].activityPrice = this.packageDetail[index].price / row.times * value
      this.packageDetail = [...this.packageDetail]
    },

    send(frequency = 1) {
      if (frequency == 0) {
        this.typepagination.current = 1
        this.typeDB.pageNum = 1
        this.typeDB.pageSize = 10
      }
      if (this.typeDB.name == '') {
        this.typeQueryParam.pageNum = 1
        this.typeQueryParam.pageSize = 10

        if (this.type == '1') {
          this.getType(true)
        } else if (this.type == '2') {
          this.getType(false)
        }
        return false
      }
      this.detailLoading = true

      searchType({ ...this.typeDB, type: this.type }).then((res) => {
        if(res.code != 200){
          this.$message.error(res.msg || res.message)
          return false
        }
        this.detailLoading = false
        if (res.code.toString() === '200') {
          res.rows.forEach((item) => {
            item.type = '2'
            item.times = '1'
            item.money = item.price
            if (this.type == '1') {
              item.basicUnit = item.itemUnit
            }
          })

          this.detailed = res.rows
          this.typepagination.total = parseInt(res.total) || 0
        }
        console.log(res)
      })
    },
    //玫瑰娃娃口液
    reset() {
      this.searchDB = {}
      this.searchDB.pageNum = 1
      this.searchDB.pageSize = 20
      this.day = []
      console.log(this.searchDB)
      this.searchDB = Object.assign({},this.searchDB)
    },
    search(type = 'search', num = '') {
      if (num == 'one') {
        this.searchDB.pageNum = 1
        this.searchDB.pageSize = 20
        this.queryParams.pageNum = 1
        this.queryParams.pageSize = 20
        this.pagination.current = 1
      }
      this.loading = true
      if (this.day && this.day.length > 0) {
        this.searchDB.start = moment(this.day[0]).format('YYYY-MM-DD') + ' 00:00:00'
        this.searchDB.end = moment(this.day[1]).format('YYYY-MM-DD') + ' 23:59:59'
      } else {
        this.searchDB.start = ''
        this.searchDB.end = ''
      }
      search(this.searchDB).then((res) => {
        if(res.code != 200){
          this.$message.error(res.msg || res.message)
          return false
        }
        this.loading = false
         
        this.data = res.rows
        console.log(this.pagination)
        this.pagination.type = type
        res.rows.forEach((item) => {
          console.log(item)
          item.isDisabled = item.isDisabled.toString() == '0' ? '已启用' : '未启用'
          item.overdueDate = item.overdueDate.toString() == '1' ? '未过期' : '已过期'
          item.subTags = item.overdueDate
          item.tags = item.isDisabled
        })
        this.pagination.total = parseInt(res.total) || 0
        console.log(res)
      })
    },
    moment,
    getType(type) {
      this.detailLoading = true
      this.type = ''
      if (type) {
        this.type = '1'
        this.name = ''
        if (this.typeDB.name != '') {
          // this.send()
          return false
        }
        getItemDetailById(this.typeQueryParam).then((res) => {
          if (res.code != 200) {
            return false
          }
          this.detailLoading = false

          for (var i = 0; i < res.rows.length; i++) {
            res.rows[i].price = res.rows[i].price
            res.rows[i].money = res.rows[i].price
            res.rows[i].unit = res.rows[i].itemUnit
          }

          this.detailed = res.rows
          this.typepagination.total = parseInt(res.total) || 0
          this.detaiColumns = [
            { title: '名称', key: 'name', dataIndex: 'name' },
            { title: '单位', key: 'itemUnit', dataIndex: 'itemUnit' },
            { title: '数量', key: 'useTimes', dataIndex: 'useTimes' },
            {
              title: '原价',
              key: 'money',
              dataIndex: 'money',
              customRender: (money) => {
                if (money == undefined || money == null) {
                  return '-'
                } else {
                  return money.toFixed('2')
                }
              },
            },
            {
              title: '执行科室',
              key: 'execDeptName',
              dataIndex: 'execDeptName',
              customRender: (execDeptName) => {
                if (!execDeptName) {
                  return '-'
                } else {
                  return execDeptName
                }
              },
            },
            // {
            //   title: '套餐价',
            //   key: 'price',
            //   dataIndex: 'price',
            //   customRender: (price) => {
            //     if (!price) {
            //       return '-'
            //     } else {
            //       price
            //     }
            //   },
            // },
          ]
          // const dept = sessionStorage.getItem('dept')
          // console.log(dept)

          console.log(res)
        })
      } else {
        this.type = '2'
        this.name = ''
        if (this.typeDB.name != '') {
          // this.send()
          return false
        }
        axios({
          url: `/product/getProductList`,
          method: 'get',
          params: this.typeQueryParam,
        }).then((res) => {
          if (res.code != 200) {
            return false
          }
          this.detailLoading = false
          res.rows.forEach((item) => {
            item.type = '2'
            item.times = '1'
            item.money = item.price
          })

          this.detailed = res.rows
          this.typepagination.total = parseInt(res.total) || 0
          this.detaiColumns = [
            {
              title: '名称',
              key: 'name',
              dataIndex: 'name',
              customRender: (name) => {
                if (!name) {
                  return '-'
                } else {
                  return name
                }
              },
            },
            {
              title: '单位',
              key: 'basicUnit',
              dataIndex: 'basicUnit',
              customRender: (basicUnit) => {
                if (!basicUnit) {
                  return '-'
                } else {
                  return basicUnit
                }
              },
            },
            {
              title: '数量',
              key: 'times',
              dataIndex: 'times',
              customRender: (times) => {
                if (!times) {
                  return '-'
                } else {
                  return times
                }
              },
            },
            {
              title: '原价',
              key: 'money',
              dataIndex: 'money',
              customRender: (money) => {
                if (money == undefined || money == null) {
                  return '-'
                } else {
                  return money.toFixed('2')
                }
              },
            },
            {
              title: '执行科室',
              key: 'execDeptName',
              dataIndex: 'execDeptName',
              customRender: (execDeptName) => {
                if (!execDeptName) {
                  return '-'
                } else {
                  return execDeptName
                }
              },
            },
            // {
            //   title: '套餐价',
            //   key: 'price',
            //   dataIndex: 'price',
            //   customRender: (price) => {
            //     if (!price) {
            //       return '-'
            //     } else {
            //       return price
            //     }
            //   },
            // },
          ]

          console.log(res)
        })
      }
    },
    async ca(expanded, record) {
      
      if (expanded && record) {
        this.openLoading = true
        this.queryParam.id = record.tbActivityId
        this.queryParam.pageNum = 1
        this.queryParam.pageSize = 20


        this.temporary.isEx = expanded
        this.temporary.record = record

        detail(Object.assign(this.queryParam)).then((res) => {
          console.log(res)
          if(res.code != 200){
            this.$message.error(res.msg || res.message)
            return false
          }
          this.openLoading = false
          if (res.code.toString() === '200') {
            res.rows.forEach((item) => {
              item.abled = item.itemIsDisabled || item.productIsDisabled
              item.abled == '0' ? (item.abled = '已启用') : (item.abled = '未启用')
              item.originalPrice = item.price * Number(item.useTimes)
              console.log(item.originalPrice)
            })
            if (res.total > 20) {
              this.loadMore = true
            }else{
              this.loadMore = false
            }
            this.innerData = res.rows
            let target = document.getElementsByClassName('ant-table-expanded-row')
            for (var i = 0; i < target.length; i++) {
              target[i].childNodes[1].colSpan = 12 //这货根据数量来推格子的?
            }
          }
        })
        this.ExpandedRowKeys = []
        this.ExpandedRowKeys.push(record.tbActivityId)
      } else {
        this.ExpandedRowKeys = []
      }
    },
    moneyChange(Num) {
      return Num.toFixed(2)
    },

    getList() {
      this.loading = true
      getActivity(this.queryParams).then((res) => {
        if(res.code != 200){
          this.$message.error(res.msg || res.message)
          return false
        }
        this.loading = false 
        res.rows.forEach((item) => {
          item.isDisabled = item.isDisabled == '1' ? '未启用' : '已启用'
          item.overdueDate = item.overdueDate == '1' ? '未过期' : '已过期'
          item.subTags = item.overdueDate
          item.tags = item.isDisabled
          if (item.totalPrice) {
            item.totalPrice = this.moneyChange(item.totalPrice)
          }
          if (item.unitPrice) {
            item.unitPrice = this.moneyChange(item.unitPrice)
          }
          if (item.packagePrice) {
            item.packagePrice = this.moneyChange(item.packagePrice)
          }
        })
        this.data = res.rows
        this.pagination.total = parseInt(res.total) || 0
        console.log(res, '获取套餐列表')
      })
    },
    addNum(total, num) {
      return total + num
    },
    add(type, record) {
      this.visible = true
      if (type === '1') {
        console.log(type)
        this.Rrecord.types = ''
        this.packageDetail = []
        this.TotalProject = '0'
        this.TotalPrice = '0'
        this.form.resetFields() //重置表单
        return
      } else if (type == '2') {
        this.loadingItem = true
        this.Rrecord = record
        this.Rrecord.types = '2'
        this.packageDetail = []
        getActivityDetail({ id: record.tbActivityId }).then((res) => {
          console.log(res)
          // 点击修改拿到活动的详情
          if(res.code != 200){
            this.$message.error(res.msg || res.message)
            return false
          }

          this.loadingItem = false
          for (var i = 0; i < res.rows.length; i++) {
            if (res.rows[i].isDisabled && res.rows[i].isDisabled === '1') {
              res.rows[i].isDisabled = false
              
            } else {
              res.rows[i].isDisabled = true
            }
 
          }
          res.rows[0].activityDetailList.map(item => {
            item.times = item.useTimes
          })
          this.form.setFieldsValue({
            activityName: res.rows[0].activityName,
            isDisabled: res.rows[0].isDisabled,
            remark: res.rows[0].remark,
            // ptype: res.rows[0].ptype,
            registDate: [res.rows[0].beginDate, res.rows[0].endDate],
          })
          this.packageDetail = [...res.rows[0].activityDetailList]
        })
      }
    },
    typeChange(pagination) {
      console.log('触发')
      this.typeQueryParam.pageNum = pagination.current
      this.typepagination.current = pagination.current
      this.typeQueryParam.pageSize = pagination.pageSize

      if (this.typeDB.name != '') {
        this.typeDB.pageNum = pagination.current
        this.typeDB.pageSize = pagination.pageSize

        this.send()
        return false
      }
      if (this.type == '1') {
        this.getType(true)
      } else if (this.type == '2') {
        this.getType(false)
      }
    },
    handleTableChange(pagination) {
      console.log(pagination)
      // this.pagination.current = pagination.current
      // this.pagination.pageSize = pagination.pageSize
      this.pagination.current = pagination.current
      this.queryParams.pageNum = pagination.current
      this.queryParams.pageSize = pagination.pageSize
      if (this.pagination.type !== 'search') {
        this.getList()
      } else {
        console.log('2')
        this.searchDB.pageNum = pagination.current
        this.searchDB.pageSize = pagination.pageSize
        this.search()
      }
    },
    clicks(record, index) {
      return {
        on: {
          dblclick: (e) => {
            // 判断当前是否存在 存在就不添加进数组
            let boolIF = this.packageDetail.find((elemt) => {
              return elemt.id == record.id || elemt.itemId == record.id
            })
            if (boolIF != undefined) {
              this.$message.error('当前数据已存在')
              return false
            }
            // this.packageDetail.push(record)
            // this.packageDetail.forEach((item) => {
            //   console.log(item)
              
            //   if (item.type === '2') {
            //     item.price = item.activityPrice  
                
            //     //type2是产品
            //     item.originalPrice = Number(item.price)
            //     // item.execDept = item.achieveDept
            //     item.activityPrice = Number(item.price * 1)
            //     item.useTimes = 1
            //     item.itemName = item.name || item.itemName
            //     item.name = item.name
            //     item.itemId = item.id
            //     item.unit = item.basicUnit
            //     item.times = 1
            //     item.money = Number(item.price)
            //     item.ex = item.execDeptName
            //     item.mainMoney = Number(item.price * 1)
            //   } else {
            //     //type1是项目
            //     // item.execDeptName = item.execDept
            //     item.originalPrice = Number(item.price)
            //     item.activityPrice = Number(item.price * 1) 
            //     item.name = item.name || item.itemName
            //     item.itemId = item.id
            //     item.itemName = item.name
            //     item.unit = item.itemUnit
            //     item.times = item.useTimes
            //     item.useTimes = item.useTimes
            //     item.money = Number(item.price)
            //     item.ex = item.achieveDept
            //     item.mainMoney = Number(item.price * item.useTimes)
            //   }
            // })



            if (record.type === '2') { 
              console.log('record:',record)
              //type2是产品
              record.originalPrice = Number(record.money)
              // record.execDept = record.achieveDept
              record.activityPrice = Number(record.money * 1)
              record.useTimes = 1
              record.itemName = record.name || record.itemName
              record.name = record.name
              record.itemId = record.id
              record.unit = record.basicUnit
              record.times = 1
              record.money = Number(record.money)
              record.ex = record.execDeptName
              record.mainMoney = Number(record.money * 1)
            } else {
              //type1是项目
              // record.execDeptName = record.execDept
              record.originalPrice = Number(record.price)
              record.activityPrice = Number(record.price * 1) 
              record.name = record.name || record.itemName
              record.itemId = record.id
              record.itemName = record.name
              record.unit = record.itemUnit
              record.times = record.useTimes
              record.useTimes = record.useTimes
              record.money = Number(record.price)
              record.ex = record.achieveDept
              record.mainMoney = Number(record.price * record.useTimes)
            }


            this.packageDetail.push(record)
            console.log('record', record, e, index, this.packageDetail)
          },
        },
      }
    },

    hide() {
      this.ShowPopover = false
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
      this.form.resetFields()
    },
    handleOk(e) {
      const {
        form: { validateFields },
      } = this
      validateFields((errors, values) => {
        if (errors) {
          console.log('表单检验未通过111', errors, values)

          return
        }
        if (this.Rrecord.tbActivityId) {
          const time = values.registDate
          values.tbActivityId = this.Rrecord.tbActivityId
          console.log('values:', values)
          if (values.isDisabled) {
            values.isDisabled = 0
          } else {
            values.isDisabled = 1
          }
          if (time && time.length > 0) {
            values.beginDate = moment(time[0]).format('YYYY-MM-DD')
            values.endDate = moment(time[1]).format('YYYY-MM-DD')
          }
          values.activityDetailList = this.packageDetail
          console.log(values)
          editActivity(Object.assign(values)).then((res) => {

            if (res.code && res.code.toString() !== '200') return this.$message.error(res.msg || res.message)
            this.visible = false
            this.Rrecord = {}
            console.log(res)
            // 暂存状态 修改之后展开
            this.ca(this.temporary.isEx, this.temporary.record)
            this.getList()
          })
          //修改提交editPackage
        } else {
          const time = values.registDate
          if (time && time.length > 0) {
            values.beginDate = moment(time[0]).format('YYYY-MM-DD')
            values.endDate = moment(time[1]).format('YYYY-MM-DD')
          }
          if (values.isDisabled) {
            values.isDisabled = 0
          } else {
            values.isDisabled = 1
          }
          values.activityDetailList = this.packageDetail
          addActivity(Object.assign(values)).then((res) => {
            if (res.code && res.code.toString() !== '200') return this.$message.error(res.msg || res.message)
            this.visible = false
            // 暂存状态 修改之后展开
            this.ca(this.temporary.isEx, this.temporary.record)
            this.getList()
          })
          //新增提交
        }
      })
    },
    handleChange(val) {
      console.log(val)
    },
    loadMores() {
      this.openLoading = true
      this.queryParam.pageNum += 1
      detail(Object.assign(this.queryParam)).then((res) => {
        if(res.code != 200){ 
          this.$message.error(res.message || res.msg)
          return false
        }
        this.openLoading = false

        res.rows.forEach((item) => {
          item.abled = item.itemIsDisabled || item.productIsDisabled
          item.abled == '0' ? (item.abled = '已启用') : (item.abled = '未启用') 
        })
        this.innerData = [...this.innerData,...res.rows]
        if (this.innerData.length.toString() === res.total.toString()) {
          this.loadMore = false
        }
      })
    },
    removeItem(record, index) {
      console.log(this.packageDetail)
      console.log(record, this.Rrecord, index)
      this.packageDetail.splice(index, 1)
      // if (record && this.Rrecord.types === '2') {
      //   removeItem({ id: record.itemId, activityId: this.Rrecord.tbActivityId }).then((res) => {
      //     if (res.code === 200) {
      //       this.$message.success(res.msg||res.message)
      //       getActivityDetail({ id: this.Rrecord.tbActivityId }).then((res) => {
      //         this.packageDetail = [...res.rows[0].activityDetailList]
      //       })
      //     } else {
      //       this.$message.error(res.message)
      //     }
      //   })
      // } else {
      //   this.packageDetail.splice(index, 1)
      //   console.log(this.packageDetail)
      // }
    },
  },
}
</script>